<script setup>


</script>

<template>
  <header>
    <div class="shelter" v-if="show"></div>
    <div class="chat_box">
      <div class="chat_list">
        <div class="list_title">{{ language.userlist }}</div>
        <transition-group class="list_box" name="anime" tag="div">
          <template v-for="(item, index) in list" :key="item.userid">
            <div class="list" :class="selectUser == item.userid ? 'listbg' : ''"
              @click="openUserValue(item.userid, item.username)">
              <div class="avatar">
                <img src="../assets/images/avatar01.jpg" alt="">
              </div>
              <div class="list_text">
                <div class="name">{{ item.username }}</div>
                <div class="id">{{language.ID}}:{{ item.userid }}</div>
              </div>
              <div class="state" v-show="item.unread == 1">{{ language.unread }}</div>
            </div>
          </template>
        </transition-group>
      </div>
      <div class="chat_content" v-if="selectUser">
        <div class="content_title">
          <div class="name">{{ selectName }}</div>
          <button @click="goUnreadable">{{ language.unreadable }}</button>
        </div>


        <div class="content_list" @click="closeDrawers">
          <template v-for="(item, index) in chatlist" :key="item.msgid">
            <div class="go_list">
              <div class="my_list" v-if="item.usertype == 0" ref="index">
                <div class="avatar" @click="gotopage('About')">
                  <img src="../assets/images/avatar01.jpg" alt="">
                </div>
                <div class="chat_text">
                  <div class="text_box">
                    <div class="text_content">
                      <div class="triangle"></div>
                      <div class="text" v-if="item.msgtype == 0">{{ item.msg }}</div>
                      <div class="img" v-if="item.msgtype == 1" @click="previewsImg(item.msg)">
                        <img :src="item.msg" alt="">
                      </div>
                      <div class="time"><span class="iconfont icon-shijian"></span> {{ conversionsTime(1742669464) }}
                      </div>
                    </div>
                    <div class="more iconfont icon-gengduo" @click.stop="openList(index)">
                      <transition name="anime">
                        <div class="drawers_box" v-if="item.open">
                          <div class="drawers" @click="copy(item.msg)">
                            <div class="text">{{ language.clone }}</div>
                            <div class="icon iconfont icon-fuzhi"></div>
                          </div>
                          <div class="drawers" @click="removingMsg(item.msgid)">
                            <div class="text">{{ language.cancel }}</div>
                            <div class="icon iconfont icon-shanchu"></div>
                          </div>
                        </div>
                      </transition>
                    </div>
                  </div>
                  <div class="name">{{ selectName }}</div>
                </div>
              </div>
              <div class="his_list" v-if="item.usertype == 1" ref="index">
                <div class="chat_text">
                  <div class="text_box">
                    <div class="more iconfont icon-gengduo" @click.stop="openList(index)">
                      <transition name="animetwo">
                        <div class="drawers_box" v-if="item.open">
                          <div class="drawers" @click="copy(item.msg)">
                            <div class="text">{{ language.clone }}</div>
                            <div class="icon iconfont icon-fuzhi"></div>
                          </div>
                          <div class="drawers" @click="removingMsg(item.msgid)">
                            <div class="text">{{ language.cancel }}</div>
                            <div class="icon iconfont icon-shanchu"></div>
                          </div>
                        </div>
                      </transition>
                    </div>
                    <div class="text_content">
                      <div class="triangle"></div>
                      <div class="text" v-if="item.msgtype == 0">{{ item.msg }}</div>
                      <div class="img" v-if="item.msgtype == 1" @click="previewsImg(item.msg)">
                        <img :src="item.msg" alt="">
                      </div>
                      <div class="time"><span class="iconfont icon-shijian"></span> {{ conversionsTime(1742669464) }}
                      </div>
                    </div>
                  </div>
                  <div class="name">{{ language.Customer }}</div>
                </div>
                <div class="avatar">
                  <img src="../assets/images/avatar02.png" alt="">
                </div>
              </div>
            </div>
          </template>
          <div class="clear_go" ref="bottom"></div>
        </div>

        <div class="input_box">
          <div class="input">
            <input type="text" :placeholder="language.pleaseenter" v-model="inputValue">
          </div>
          <div class="image iconfont icon-tupian">
            <van-uploader
              style="opacity: 0;position: absolute;left: 0;top: 0;z-index: 90;width: 100%;height: 45px;overflow: hidden;"
              :after-read="afterRead" multiple />
          </div>

          <div class="sending iconfont icon-fasong" @click="sendMessage"></div>


        </div>
      </div>
      <div v-else class="nomessages iconfont icon-zanwuxiaoxi"></div>
    </div>
  </header>


</template>

<script>
import moment from 'moment';
import axios from 'axios';
import { ref } from 'vue';
import Lang from '../../public/lang/cn.json';
import http from '@/util/http';
import Cfg from '@/util/config';
import { showLoadingToast, showConfirmDialog, showImagePreview, showToast, Uploader, closeToast } from 'vant';
export default {
  components: {
    [Uploader.name]: Uploader
  },
  // 组件选项
  data() {
    return {
      // 数据对象
      list: ref([]),
      listlastts: 0,
      chatlist: ref([]),
      chatmsgid: 0,
      timer: null,
      timer02: null,
      show: true,
      selectUser: '',
      selectName: '',
      copyValue: '',
      inputValue: '',
      language: '',
    };
  },
  computed: {
    
  },
  mounted() {
    // this.scrollToBottom();
    this.language = Lang
    setTimeout(() => {
      this.show = false;
      closeToast();


    }, 1000);

    localStorage.removeItem('listUpdate');
    this.getUseList();


  },
  created() {
    this.startTimer();

  },
  beforeCreate() {
    showLoadingToast({
      message: '加载中...',
      duration: 0, // 持续展示 toast
    })
  },
  beforeUnmount() {
    clearInterval(this.timer);
    clearInterval(this.timer02);
  },
  methods: {
    afterRead(file) {
      // 可以在这里处理文件，例如上传到服务器
      // console.log(file); // 文件信息
      // console.log(Cfg.file)
      showLoadingToast({
        message: '加载中...',
        duration: 0, // 持续展示 toast
      })
      this.uploadFile(file.file); // 上传文件的方法
    },
    uploadFile(file) {
      const formData = new FormData();
      formData.append('file', file);
      //console.log(formData);
      // 发送到服务器，这里使用axios作为示例
      axios.post(`${Cfg.file}/upload.php`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        showToast('上传成功');
        var msgtype = 1;
        var datalist = http.post(`/users/sendmsg.do?userid=${this.selectUser}&msgtype=${msgtype}&msg=${formData}`);
        closeToast();
        this.openUserValue02();
      }).catch(error => {
        showToast('上传失败');
      });
    },
    removingMsg(msgid) {
      let that = this;
      showConfirmDialog({
        title: '提示',
        message: '是否删除？',
        confirmButtonColor: '#7269ef'
      })
        .then(() => {
          // on confirm
          var datalist = http.post(`/users/deletemsg.do?userid=${this.selectUser}&msgid=${msgid}`);
          showToast('删除成功');
          this.openUserValue02();
        }).catch(() => {
          // on cancel
          showToast('点击取消');
        });
    },
    sendMessage() {
      let that = this;
      showConfirmDialog({
        title: '提示',
        message: '是否发送',
        confirmButtonColor: '#7269ef'
      })
        .then(() => {
          // on confirm
          var msgtype = 0;
          if (!this.inputValue) {
            showToast('请输入想要说的话');
            return
          }
          showLoadingToast({
            message: '加载中...',
            duration: 0, // 持续展示 toast
          })
          var datalist = http.post(`/users/sendmsg.do?userid=${this.selectUser}&msgtype=${msgtype}&msg=${this.inputValue}`);
          this.inputValue = '';
          closeToast();
          showToast('发送成功');
          this.openUserValue02();

        }).catch(() => {
          // on cancel
          showToast('点击取消');
        });
    },
    goUnreadable() {
      let that = this;

      showConfirmDialog({
        title: '提示',
        message: '是否已读不回？',
        confirmButtonColor: '#7269ef'
      })
        .then(() => {
          // on confirm
          showLoadingToast({
            message: '加载中...',
            duration: 0, // 持续展示 toast
          })
          var datalist = http.post(`/users/setread.do?userid=${this.selectUser}`);
          closeToast();
          showToast('设置成功');
        }).catch(() => {
          // on cancel
          showToast('点击取消');
        });
    },
    conversionsTime(time) {
      return moment(time * 1000).format('YYYY-MM-DD HH:mm:ss')
    },
    async openUserValue(userid, name) {
      if (this.timer02) {
        clearInterval(this.timer02);
      }

      showLoadingToast({
        message: '加载中...',
        duration: 0, // 持续展示 toast
      })

      this.chatlist = [];
      this.selectUser = userid;
      this.selectName = name;

      try {
        var datalist = await http.post(`users/getmsg.do?userid=${this.selectUser}&msgid=${this.chatmsgid}`);
        var msglist = datalist.body.msglist;

        msglist.map((item, index) => {
          item.open = false; //添加的字段
        })
        this.chatlist = msglist;
        setTimeout(() => {
          this.scrollToBottom();
        }, 300);

        closeToast();

        this.startTimer02();

      } catch (error) {
        showToast(error);
      }


    },
    async openUserValue02() {
      try {
        var datalist = await http.post(`users/getmsg.do?userid=${this.selectUser}&msgid=${this.chatmsgid}`);
        var msglist = datalist.body.msglist;
        msglist.map((item, index) => {
          item.open = false; //添加的字段
        })

        if (msglist.length != this.chatlist.length) {
          const originalIds = this.chatlist.map(item => item.msgid);
          const addValue = msglist.filter(item => !originalIds.includes(item.msgid));
          this.chatlist.push(addValue[0]);
          setTimeout(() => {
            this.scrollToBottom();
          }, 300);
        }

      } catch (error) {
        showToast(error);
      }


    },
    startTimer() {
      this.timer = setInterval(() => {
        if (localStorage.getItem('listUpdate')) {
          this.listlastts = localStorage.getItem('listUpdate');
          this.getUseList02()
        }

      }, 5000);
    },
    startTimer02() {
      this.timer02 = setInterval(() => {
        this.openUserValue02()

      }, 5000);
    },
    async getUseList() {
      try {
        showLoadingToast({
          message: '加载中...',
          duration: 0, // 持续展示 toast
        })
        var datalist = await http.post(`/users/userlist.do?lastts=${this.listlastts}`);
        this.list = datalist.body.userlist;
        closeToast();
        localStorage.setItem('listUpdate', datalist.body.lastts);

      } catch (error) {
        showToast(error);
      }
    },
    async getUseList02() {
      try {
        var datalist = await http.post(`/users/userlist.do?lastts=${this.listlastts}`);
        var addlist = datalist.body.userlist;

        if (addlist.length != this.list.length) {
          const originalIds = this.list.map(item => item.userid);
          const addValue = addlist.filter(item => !originalIds.includes(item.userid));
          this.list.splice(0, 0, addValue[0]);
        } else {
          for (let index = 0; index < addlist.length; index++) {
            if (this.list[index].unread != addlist[index].unread && this.list[index].userid == addlist[index].userid) {
              this.list[index].unread = addlist[index].unread
            }

          }
        }
      } catch (error) {
        showToast(error);
      }
    },
    previewsImg(url) {
      console.log(url)
      showImagePreview({
        images: [
          url
        ],
        startPosition: 0,
        closeable: true,
      });
    },
    copy(data) {
      showConfirmDialog({
        title: '提示',
        message: '是否复制?',
        confirmButtonColor: '#7269ef'
      })
        .then(() => {
          let url = data;
          let oInput = document.createElement('input');
          oInput.value = url;
          document.body.appendChild(oInput);
          oInput.select();
          console.log(oInput.value);
          document.execCommand("Copy");
          oInput.remove()
          showToast('复制成功');
        })
        .catch(() => {
          showToast('复制失败');
        });

    },
    scrollToBottom() {
      this.$refs.bottom.scrollIntoView({ behavior: 'smooth' });
    },
    openList(index) {
      this.chatlist.forEach(res => {
        res.open = false;
      });
      this.chatlist[index].open = true;
    },
    closeDrawers() {
      this.chatlist.forEach(res => {
        res.open = false;
      });
    },
    gotopage(url) {
      let statedata = {
        name: this.selectName,
        userid: this.selectUser,
      }
      this.$router.push({ name: url, state: statedata })
    }
  },

}
</script>

<style scoped></style>
